package it.kion.util.ui.ulog2.editor.contentassist;

import java.io.*;
import java.util.*;

public class ConfigurationModel {
	private static String baseProps[] = { "log4j", "log4j.additivity",
			"log4j.appender", "log4j.category", "log4j.factory",
			"log4j.logger", "log4j.renderer", "log4j.rootCategory",
			"log4j.rootLogger", "log4j.threshold" };

	private Properties properties;
	private String rootLogger;
	private String[] appenders;

	public ConfigurationModel(String configuration) throws IOException {
		properties = new Properties();
		properties.load(new ByteArrayInputStream(configuration.getBytes()));
		rootLogger = properties.getProperty("log4j.rootLogger");
		appenders = parseCategory(rootLogger);
	}

	public List<String> getCompletions(String prefix) {
		List<String> completions = new LinkedList<String>();

		for (int i = 0; i < appenders.length; i++) {
			if (testCompletion(appenders[i], prefix)) {
				completions.add(appenders[i]);
			}
		}
		for (int i = 0; i < baseProps.length; i++) {
			if (testCompletion(baseProps[i], prefix)) {
				completions.add(baseProps[i]);
			}
		}
		return completions;
	}

	private boolean testCompletion(String completion, String prefix) {
		return completion.toLowerCase().startsWith(prefix.toLowerCase())
				&& (completion.lastIndexOf(".") == prefix.lastIndexOf("."));
	}

	private String[] parseCategory(String value) {
		List<String> appenders = new LinkedList<String>();

		if (value != null) {
			StringTokenizer st = new StringTokenizer(value, ",");

			if (!(value.startsWith(",") || value.equals(""))) {
				st.nextToken();
			}

			while (st.hasMoreTokens()) {
				String appenderName = st.nextToken().trim();
				if (appenderName == null || appenderName.equals(","))
					continue;
				appenders.add("log4j.appender." + appenderName);
			}
		}
		return appenders.toArray(new String[0]);
	}
}
